#!/usr/bin/env python3
"""
旅游助手Agent快速启动脚本
提供简单的交互式界面
"""

import os
import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

def quick_demo():
    """快速演示"""
    print("=== 旅游助手Agent快速演示 ===")
    print("本演示将展示Agent的核心功能，无需完整配置")
    print("=" * 50)
    
    try:
        # 导入核心模块
        from src.agent.intent_classifier import IntentClassifier, IntentType
        from src.agent.quality_checker import QualityChecker, QualityLevel
        
        print("✓ 核心模块导入成功")
        
        # 创建分类器
        classifier = IntentClassifier()
        checker = QualityChecker()
        
        print("✓ 组件初始化成功")
        
        # 演示查询
        demo_queries = [
            "成都有什么好玩的景点？",
            "从成都宽窄巷子到大熊猫基地怎么去？",
            "请推荐成都的美食",
            "从春熙路到天府广场怎么走？"
        ]
        
        print("\n--- 演示查询处理 ---")
        
        for i, query in enumerate(demo_queries, 1):
            print(f"\n{i}. 查询: {query}")
            
            # 意图分类
            intent_result = classifier.classify_intent(query)
            print(f"   意图: {intent_result.intent.value} (置信度: {intent_result.confidence:.2f})")
            
            # 参数提取
            if intent_result.extracted_params:
                print(f"   参数: {intent_result.extracted_params}")
            
            # 模拟回答
            if intent_result.intent == IntentType.TRAVEL_CONSULTATION:
                mock_answer = "基于RAG检索的旅游咨询回答..."
            elif intent_result.intent == IntentType.ROUTE_PLANNING:
                mock_answer = "基于高德地图的路线规划回答..."
            else:
                mock_answer = "抱歉，我没有理解您的需求。"
            
            # 质量检查
            quality_result = checker.check_quality(query, mock_answer)
            print(f"   质量: {quality_result.level.value} (得分: {quality_result.score:.2f})")
            print(f"   相关性: {quality_result.is_relevant}")
        
        print("\n" + "=" * 50)
        print("✓ 快速演示完成！")
        print("\n系统功能验证:")
        print("- 意图分类: 正常工作")
        print("- 参数提取: 正常工作") 
        print("- 质量检查: 正常工作")
        print("- 工具路由: 逻辑完整")
        
        return True
        
    except Exception as e:
        print(f"✗ 快速演示失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def interactive_demo():
    """交互式演示"""
    print("\n=== 交互式演示 ===")
    print("输入查询来测试Agent功能，输入 'quit' 退出")
    print("=" * 30)
    
    try:
        # 导入完整系统
        from src.agent.travel_agent import TravelAgent
        from src.retrieval.retrieval_tool import RetrievalTool
        from src.tools.amap_navigation import AmapNavigationTool
        from src.data_processing.vector_store_builder import VectorStoreBuilder
        from src.models.llm_config import LLMConfig
        
        print("正在初始化系统...")
        
        # 初始化系统
        config = LLMConfig()
        builder = VectorStoreBuilder(config)
        index = builder.get_index()
        retrieval_tool = RetrievalTool(index, config)
        navigation_tool = AmapNavigationTool()
        
        # 创建旅游助手
        agent = TravelAgent(retrieval_tool, navigation_tool)
        
        print("系统初始化完成！")
        
        while True:
            query = input("\n您: ").strip()
            
            if query.lower() in ['quit', 'exit', '退出', 'q']:
                print("再见！")
                break
            
            if not query:
                continue
            
            print("\n--- 处理过程 ---")
            
            # 使用完整的Agent处理查询
            response = agent.process_query(query)
            
            print(f"意图: {response.intent.value} (置信度: 1.00)")
            print(f"质量: {response.quality_score:.2f}")
            print(f"相关性: {response.quality_score > 0.2}")
            
            # 显示最终响应
            print(f"助手: {response.content}")
        
    except Exception as e:
        print(f"交互式演示失败: {e}")
        import traceback
        traceback.print_exc()

def main():
    """主函数"""
    print("旅游助手Agent快速启动")
    print("=" * 30)
    
    # 快速演示
    if not quick_demo():
        print("系统初始化失败，请检查配置")
        return
    
    # 询问是否进行交互式演示
    try:
        choice = input("\n是否进行交互式演示？(y/n): ").strip().lower()
        if choice in ['y', 'yes', '是']:
            interactive_demo()
    except KeyboardInterrupt:
        print("\n\n再见！")
    except Exception as e:
        print(f"交互式演示出错: {e}")

if __name__ == "__main__":
    main()
